/**
 * Alibaba.com.cn Inc.
 * Copyright (c) 2004-2021 All Rights Reserved.
 */
package com.smart.common.interceptor;

import com.smart.common.Constants;
import com.smart.context.BaseSession;
import com.smart.context.SessionContext;
import com.smart.model.vo.JiansheUnitVO;
import com.smart.model.vo.OperateUserVO;
import com.smart.model.vo.ProjectVO;
import com.smart.model.vo.SuperviseUserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zhanghong
 * @version HeaderInterceptor.java, v 0.1 2023/6/22 21:48 下午 HeaderInterceptor Exp $$
 */
@Slf4j
public class HeaderInterceptor implements AsyncHandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        Object object = request.getSession().getAttribute(Constants.LOGIN_USER);
        if (object != null) {
            if (object instanceof ProjectVO) {
                ProjectVO projectVO = (ProjectVO) object;
                SessionContext.context.set(BaseSession.builder().project(projectVO).build());
            } else if (object instanceof OperateUserVO) {
                OperateUserVO operateUserVO = (OperateUserVO) object;
                SessionContext.context.set(BaseSession.builder().operateUser(operateUserVO).build());
            } else if (object instanceof SuperviseUserVO) {
                SuperviseUserVO superviseUserVO = (SuperviseUserVO) object;
                SessionContext.context.set(BaseSession.builder().superviseUser(superviseUserVO).build());
            } else if (object instanceof JiansheUnitVO) {
                JiansheUnitVO jiansheUnitVO = (JiansheUnitVO) object;
                SessionContext.context.set(BaseSession.builder().jiansheUnit(jiansheUnitVO).build());
            }
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        SessionContext.context.remove();
    }
}
